package com.sigmatrix.h5.aop;

import org.apache.log4j.Logger;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;

import com.alibaba.fastjson.JSONObject;

/**
 * 
 *@ClassName: LogAspect
 *@Description: 打印日志
 *@author MH
 *@date 2017年11月7日 上午10:26:39
 */
@Aspect
@Component
public class LogAspect {
	
	private Logger logger = Logger.getLogger("a");
	
	private String name;
	
	@Pointcut("@annotation(io.swagger.annotations.ApiOperation)")
	public void ponitCut(){}
	
	/**
	 * 
	 *@Title: printParam
	 *@Description: 打印参数
	 *@return void
	 *@author MH
	 *@date 2017年11月7日 上午10:51:27
	 *@param point
	 */
	@Before(value = "ponitCut()")
	public void printParam(JoinPoint point){
		Object[] args = point.getArgs();
		Signature method = point.getSignature();
		Object target = point.getTarget();
		name = target.getClass().getName()+"#"+method.getName();
		try {
			logger.info(String.format("%s参数：%s", name,JSONObject.toJSONString(args)));
		}catch(Throwable e) {
			
		}
	}
	
	/**
	 * 
	 *@Title: printResult
	 *@Description: 打印结果
	 *@return void
	 *@author MH
	 *@date 2017年11月7日 上午10:51:37
	 *@param point
	 *@param result
	 */
	@AfterReturning(pointcut="ponitCut()",returning="result")
	public void printResult(JoinPoint point,Object result){
		String str = "";
		if((str = JSONObject.toJSONString(result)).length() > 1000)
			str = str.substring(0, 1000)+"...";
		logger.info(String.format("%s返回结果：%s", name,str));
	}
	
	@AfterThrowing(pointcut="ponitCut()",throwing="e")
	public void exceptionResult(JoinPoint joinPoint,Throwable e){
		logger.info(String.format("%s返回结果：%s", name,e.getMessage()));
	}
	/**
	 * 
	 *@Title: rabbitException
	 *@Description:消息队列异常以后线程休一段时间
	 *@return void
	 *@author MH
	 *@date 2018年1月30日 上午10:08:43
	 *@param joinPoint
	 *@param e
	 */
	@AfterThrowing(pointcut="@annotation(org.springframework.amqp.rabbit.annotation.RabbitListener)",throwing="e")
	public void rabbitException(JoinPoint joinPoint,Throwable e){
		try {
			logger.error(e.getMessage(), e);
			Thread.sleep(100000);
		} catch (InterruptedException e1) {
			e.addSuppressed(e1);
		}
		throw new RuntimeException(e);
	}
	
	
	
	
	
	
}
